package org.uned.agonzalo16.bitacora.web.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.uned.agonzalo16.bitacora.service.security.AuthenticatedUser;
import org.uned.agonzalo16.bitacora.service.security.AuthenticationProvider;

public class SessionPopulateInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = Logger.getLogger(SessionPopulateInterceptor.class);

	@Autowired
	private AuthenticationProvider authenticationProvider;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

		HttpSession session = request.getSession(false);

		if (session == null) {
			return true;
		}

		if (session.getAttribute("userAttribute") != null) {
			return true;
		}

		AuthenticatedUser user = authenticationProvider.getCurrentUserDetails();
		if (user != null) {
			logger.info("Selecting user info: " + user);
			session.setAttribute("userAttribute", user);
		}

		return true;
	}
}
